package linker.plugin;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import linker.account.ManageAccount;
import linker.file.FileFunction;

/**
 * 
 * @version linker 0.93
 * @author Jianfeng jianfeng.linker@gmail.com
 * 
 */
public class PluginShare { 

	public static void sendPlugin(String currentJID, File file) {
		String path = ManageAccount.getPath() + "plugins";

		try {
			File zip = new File(path + File.separator + file.getName() + ".zip");
			if (!zip.exists()) {
				FileOutputStream f = new FileOutputStream(zip.getAbsolutePath());
				CheckedOutputStream csum = new CheckedOutputStream(f,
						new Adler32());
				ZipOutputStream zos = new ZipOutputStream(csum);
				BufferedOutputStream out = new BufferedOutputStream(zos);

				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().endsWith("~"))
						continue;
					BufferedReader in = new BufferedReader(new FileReader(
							files[i]));
					zos.putNextEntry(new ZipEntry(files[i].getName()));

					int c;
					while ((c = in.read()) != -1)
						out.write(c);

					in.close();
					out.flush();
				}

				out.close();
			}

			FileFunction.sendPlugin(currentJID, zip);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void recivePlugin(String filePath) {
		File file = new File(filePath.substring(0, filePath.length() - 4));
		if (file.exists())
			return;

		file.mkdir();

		try {
			FileInputStream fi = new FileInputStream(filePath);
			CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
			ZipInputStream in2 = new ZipInputStream(csumi);
			BufferedInputStream bis = new BufferedInputStream(in2);
			ZipEntry ze;
			while ((ze = in2.getNextEntry()) != null) {
				File temp = new File(file.getAbsolutePath()
						+ ManageAccount.getFileSeparator() + ze.getName());
				BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
				int x;
				while ((x = bis.read()) != -1) {
					writer.write(x);
				}
				writer.flush();
				writer.close();
			}
			bis.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
